<template>
  <div class="s-echart" :style="wrapStyle">
    <div ref="mainRef" v-bind="{ style: echartStyle }" />
  </div>
</template>

<script>
import * as echarts from 'echarts'
const isNumber = function (val) {
  const regPos = /^\d+(\.\d+)?$/ // 非负浮点数
  const regNeg = /^(-(([0-9]+\.[0-9]*[1-9][0-9]*)|([0-9]*[1-9][0-9]*\.[0-9]+)|([0-9]*[1-9][0-9]*)))$/
  // 负浮点数
  if (regPos.test(val) || regNeg.test(val)) {
    return true
  } else {
    return false
  }
}
export default {
  props: {
    option: {
      type: Object,
      default: () => {
        return null
      },
    },
    width: {
      type: [Number, String],
      default: 200,
    },
    height: {
      type: [Number, String],
      default: 200,
    },
    isScale: {
      type: Boolean,
      default: () => true,
    },
    isZoom: {
      type: Boolean,
      default: () => true,
    },
  },
  data() {
    return {
      echart: undefined,
    }
  },
  computed: {
    wrapStyle() {
      // const { zoom } = store.getters
      const style = Object.assign(this.getSize(), {})
      if (this.isScale) {
        // style.transform = `scale(${zoom})`
        style.transformOrigin = '0% 0%'
      }
      // if (props.isZoom) {
      //   style.zoom = 1 / zoom
      // }
      return style
    },
    echartStyle() {
      return {
        width: '100%',
        height: '100%',
      }
    },
  },
  watch: {
    option: {
      handler() {
        this.init()
      },
      deep: true,
    },
  },
  mounted() {
    this.init()
  },
  methods: {
    init() {
      if (!this.option) return
      if (!this.echart) {
        this.echart = echarts.init(this.$refs.mainRef, undefined, this.option)
      }
      this.echart.setOption(this.option, true)
    },
    getSize() {
      return {
        width: isNumber(this.width) ? this.width + 'px' : this.width,
        height: isNumber(this.height) ? this.height + 'px' : this.height,
      }
    },
    redraw() {
      if (this.echart) {
        this.echart.resize()
      }
    },
  },
}
</script>

